/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <p>Project: javaweb - Download
 * <p>Powered by webrx On 2022-03-14 11:49:29
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@WebServlet("/down")
public class Download extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        if(req.getParameter("f")==null){

        }else{
            String filename = req.getParameter("f");
            String filePath = req.getServletContext().getRealPath("/WEB-INF/down/" + filename);
            File file = new File(filePath);
            // 读到流中
            FileInputStream fis = new FileInputStream(filePath);// 文件的存放路径

            resp.addHeader("Content-Length", "" + file.length());
            resp.setContentType("application/octet-stream");

            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
            //依日期的方式来重新命名新文件 如: 20210625101023234.rar
            filename = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")).concat(filename.substring(filename.lastIndexOf(".")));
            resp.addHeader("Content-Disposition", "attachment; filename="+filename);
            OutputStream os = resp.getOutputStream();
            // 循环取出流中的数据
            byte[] b = new byte[1024];
            int len;
            try {
                while ((len = fis.read(b)) > 0) {
                    os.write(b, 0, len);
                }
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            os.flush();
            os.close();
        }

    }
}
